package com.emedinaa.kotlinmvvm.viewmodel

import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class MyMediatorViewModel(): ViewModel() {
    val liveData1 = MutableLiveData<Int>()
    val liveData2 = MutableLiveData<Int>()
    val mediatorLiveDataSum = MediatorLiveData<Int>()

    init {
        mediatorLiveDataSum.apply {
            addSource(liveData1) {
                mediatorLiveDataSum.value = sum()
            }
            addSource(liveData2) {
                mediatorLiveDataSum.value = sum()
            }

        }
    }

    fun sum():Int{
        return (liveData1.value ?: 0) + (liveData2.value ?: 0)
    }
}